package com.freshcity.page.tree
{
	import com.freshcity.component.container.Component;
	import com.freshcity.component.guide.GuideTipsManager;
	import com.freshcity.core.Dispatcher;
	import com.freshcity.core.FilterConst;
	import com.freshcity.core.GlobalVar;
	import com.freshcity.core.MainScene;
	import com.freshcity.core.OpCodes;
	import com.freshcity.lib.event.EventName;
	import com.freshcity.lib.tooltip.ToolTipsManager;
	import com.freshcity.manager.EffectManager;
	import com.freshcity.manager.MsgManager;
	import com.freshcity.manager.support.MaskInfo;
	import com.freshcity.page.feiji.FeiJiWriter;
	import com.freshcity.tree.OutWaterWin;
	import com.freshcity.utils.GlobalUtil;
	import com.freshcity.utils.MessageUtil;
	import com.greensock.TweenLite;
	
	import fl.events.ListEvent;
	
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.geom.Point;
	import flash.text.StyleSheet;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;

	public class MyTree extends Component
	{
		private var back:OutWaterWin;
		private var waterBar:WaterBar;
		private var logTf:TextField;
		private static const CSS:String="".concat('.my_status{color: #C5C5C5;letter-spacing:4px;}', "a{color: #2595B7;}", ".c_tx4{color: #FE6600;}", "div{display: block;}", "span{}", "");
		private var growValue:int;
		private var data:*;
		private var feijiWriter:FeiJiWriter;

		public function MyTree(parent:DisplayObjectContainer=null, xpos:Number=0, ypos:Number=0)
		{
			super(parent, xpos, ypos);
			back.jiaoshuiBtn.addEventListener(MouseEvent.CLICK, onJiaoshuiBtnClick);
			this.waterBar.addEventListener(Event.SELECT,onWaterSelectHandler);
			back.newFeijiLink.addEventListener(TextEvent.LINK, onNewFeijiClick);
			back.logPanel.tabMenu.addEventListener(ListEvent.ITEM_CLICK, onRenderTreeLog);
		}
		
		private function onNewFeijiClick(event:Event):void
		{
			if(main.user.permitFeiji<=0){
				main.msg.showRollTipsMsg("今日可投纸飞机名额已经用完");
				return;
			}
			feijiWriter.onShow();
		}
		
		private function onRenderTreeLog(event:ListEvent):void
		{
			var index:int=event.index;
			switch(index)
			{
				case 1:
				{
					logTf.htmlText = MessageUtil.friendRank(data.friendRank as Array,true);
					break;
				}
					
				default:
				{
					logTf.htmlText = MessageUtil.decodeTreeLog(data.treeLog);
					break;
				}
					back.logPanel.panel.update();
			}
		}		
		
		protected function onWaterSelectHandler(event:Event):void
		{
			back.errorTip.visible = false;
		}
		
		protected function onJiaoshuiBtnClick(event:MouseEvent):void
		{
			if (main.user.energy < GlobalVar.POURE_WATER_ENERGY){
				main.msg.showRollTipsMsg("今日体力已经不足");
				return;
			}
			
			if (this.growValue <= 0)
			{
				this.reqNewTree();
			}
			else if (this.growValue >= GlobalVar.MAX_TREE_LEVEL*GlobalVar.UPGRADE_LEVEL_VALUE)
			{
				this.reqCrop();
			}
			else
			{
				this.reqWatering();
			}
		}

		private function reqNewTree():void
		{
			back.jiaoshuiBtn.labelName.text="工作中...";
			switchBtnStatus(false);
			main.statusPanel.timeBar.data=48;
			main.statusPanel.timeBar.callBackFun=reqNewTreeCallback;
		}
		
		private function reqNewTreeCallback():void
		{
			main.commu.send(OpCodes.INIT_MY_TREE, {}, initMyTreeCallback);
		}
		
		private function initMyTreeCallback(data:*):void
		{
			if(!GlobalUtil.guideIsDone(2)){
				TweenLite.delayedCall(1,onShowGuide);
			}else{
				main.msg.showFixRollMsg("种树成功，小树正等着浇水长大...");
			}
			setTreeData(data);
		}
		
		private function forwardPage():void
		{
			main.guideTip.hideGuideTips();
			main.commu.send(OpCodes.GUIDE_DONE, {indexPos:2});
		}
		
		private function onShowGuide():void
		{
			var s:String = "真棒！栽种成功。但这只是开始，坚持浇水,小树才能最终长大。";
			main.guideTip.getGuideTips(s,jiaoshuiGuide,0,null,false);
		}
		
		private function jiaoshuiGuide():void
		{
			EffectManager.hideUIMask();
			main.guideTip.hideGuideTips();
			var s:String = "点击这里浇水";
			var position:Point = new Point(495,406);
			var size:Point = new Point(104,28);
			
			var loc1:MaskInfo=new MaskInfo(position,size);
			//EffectManager.addUIMask([loc1],0);
			GuideTipsManager.getLineBoxTips(s,loc1,null,1000,GuideTipsManager.Dir_BL);			
		}
		
		private function onShowGuide2():void
		{
			var s:String = "当存水不足时，需要清水补充。邀请他人帮你采水，是最佳方案！否则，你只好自己采水。";
			main.guideTip.getGuideTips(s,caishuiGuide,0,null,false);
		}		
		
		private function caishuiGuide():void
		{
			EffectManager.hideUIMask();
			main.guideTip.hideGuideTips();
			var s:String = "点击这里亲自采水";
			var position:Point = new Point(154,108);
			var size:Point = new Point(80,28);
			
			var loc1:MaskInfo=new MaskInfo(position,size);
			//EffectManager.addUIMask([loc1],0);
			GuideTipsManager.getLineBoxTips(s,loc1,null,3000,GuideTipsManager.Dir_BL);
			main.commu.send(OpCodes.GUIDE_DONE, {indexPos:2});
		}

		private function reqCrop():void
		{
			var xinyuan:XinYuanGuo=new XinYuanGuo();
			xinyuan.tree=this;
			xinyuan.main=this.main;
			xinyuan.show();
		}

		private function reqWatering():void
		{
			if (!waterBar.hasWater()){
				back.errorTip.label.text = "没有存水，先去采水吧";
				back.errorTip.visible = true;
			}else if(!waterBar.selectedItem){
				back.errorTip.label.text = "请先选择一份清水";
				back.errorTip.visible = true;
			}else{
				back.errorTip.visible = false;
				back.jiaoshuiBtn.labelName.text="工作中...";
				switchBtnStatus(false);				
				main.statusPanel.timeBar.data=48;
				main.statusPanel.timeBar.callBackFun=onFinishTimeCallback;
				//main.commu.send(OpCodes.REQ_OUT_WATER, {water: waterBar.selectedItem.index}, reqOutWaterCallback);
			}
		}

		private function onFinishTimeCallback():void
		{
			main.commu.send(OpCodes.FINISH_OUT_WATER, {water: waterBar.selectedItem.index}, finishCallBack);
		}

		private function finishCallBack(data:*):void
		{
			if (data==-2)
			{
				main.msg.showRollTipsMsg("今日体力已不足");
			}
			else
			{
				main.msg.showFixRollMsg("使用" + MessageUtil.decodeWater(data) + "完成一次浇水");
				if(!GlobalUtil.guideIsDone(2)){
					onShowGuide2();
				}
			}
		}

		override protected function addChildren():void
		{
			super.addChildren();
			back=new OutWaterWin();
			addChild(back);

			back.jiaoshuiBtn.buttonMode=true;
			back.errorTip.visible=false;
			waterBar=new WaterBar(back, 105, 262);
			
			var style1:StyleSheet=new StyleSheet();
			style1.setStyle("a:link", {color: '#0000FF', fontSize: '12'});
			style1.setStyle("a:hover", {color: '#ff0000', textDecoration: 'underline', fontSize: '12'});
			
			back.newFeijiLink.x = 60;
			back.newFeijiLink.y = 296;
			back.newFeijiLink.visible=true;
			back.newFeijiLink.styleSheet=style1;
			back.newFeijiLink.htmlText="<a href='event:'>"+">>没有存水了?求支援!"+"</a>";
			feijiWriter = new FeiJiWriter(null,0,0,"<font color='#9D9D9D'>谁来帮我呀? 我的梧桐树正需要清水！</font>");

			//初始化成长动态
			logTf=new TextField();
			logTf.x=5;
			logTf.y=20;
			logTf.autoSize=TextFieldAutoSize.LEFT;
			logTf.wordWrap=true;
			logTf.multiline=true;
			logTf.width=220;

			var format:TextFormat=new TextFormat("宋体", 12);
			format.leading=6;
			logTf.defaultTextFormat=format;

			var style:StyleSheet=new StyleSheet();
			style.parseCSS(MyTree.CSS);
			logTf.styleSheet=style;

			back.logPanel.panel.source=logTf;
		}
		
		override public function set main(value:MainScene):void
		{
			super.main = value;
			feijiWriter.main = this.main;
		}

		override public function show(event:Event=null):void
		{
			logTf.addEventListener(TextEvent.LINK, main.onAboutUser);
			EffectManager.addLoadMask(back);
			waterBar.main=this.main;
			waterBar.show(event);
			super.show();
			main.commu.send(OpCodes.GET_MY_TREE, {}, setTreeData);
			Dispatcher.addEventListener(EventName.FinishTimeTick, renderTree);
		}

		private function switchBtnStatus(flag:Boolean):void
		{
			back.jiaoshuiBtn.mouseEnabled=flag;
			back.jiaoshuiBtn.mouseChildren=flag;
			back.jiaoshuiBtn.labelName.mouseEnabled=false;
		}

		public function setTreeData(data:*):void
		{
			this.data=data;
			renderTree();
		}

		private function renderTree(event:Event=null):void
		{
			EffectManager.hideLoadMask();
			if (data.growValue == undefined)
			{
				back.jiaoshuiBtn.labelName.text="立刻种树";
				back.treeItem.gotoAndStop(1);
				switchMyTreeStatus(false);
				return;
			}
			
			this.growValue=data.growValue;
			var maxValue:int = GlobalVar.MAX_TREE_LEVEL*GlobalVar.UPGRADE_LEVEL_VALUE;
			var i:int = (data.growValue/maxValue)*back.growBar.totalFrames;
			back.growBar.gotoAndStop(i);
			back.growBar.toolTipData= "成长度 "+ data.growValue +"/"+ maxValue;
			ToolTipsManager.register(back.growBar);
			main.user.waterInfo=data.waterInfo;
			waterBar.setData(main.user.waterInfo);
			
			back.logPanel.tabMenu.selectedIndex = 0;
			logTf.htmlText=MessageUtil.decodeTreeLog(data.treeLog, true);
			back.logPanel.panel.update();

			back.jiaoshuiBtn.filters=[];
			waterBar.selectedItem=null;
			switchMyTreeStatus(true);
			
			if (this.growValue >= maxValue)
			{
				back.jiaoshuiBtn.labelName.text="立刻收获";
				back.treeItem.gotoAndStop(data.growLevel + 1);
			}
			else
			{
				back.jiaoshuiBtn.labelName.text="开始浇水";
				back.treeItem.gotoAndStop(data.growLevel + 1);
			}

			if (main.statusPanel.timeBar.isTick)
			{
				back.jiaoshuiBtn.labelName.text="工作中...";
				switchBtnStatus(false);
			}
			else
			{
				switchBtnStatus(true);
			}
			
			if (main.user.energy < GlobalVar.POURE_WATER_ENERGY)
			{
				back.jiaoshuiBtn.filters=[FilterConst.colorMatrixFilterGray];
			}
		}
		
		private function switchMyTreeStatus(flag:Boolean):void
		{
			back.growBar.visible=flag;
			back.logPanel.visible=flag;
			back.newFeijiLink.visible=flag;
			this.waterBar.visible=flag;
		}

		override public function destroy():void
		{
			back.errorTip.visible = false;
			ToolTipsManager.unregister(back.growBar);
			Dispatcher.removeEventListener(EventName.FinishTimeTick, renderTree);
			logTf.removeEventListener(TextEvent.LINK, main.onAboutUser);
			back.jiaoshuiBtn.removeEventListener(MouseEvent.CLICK, onJiaoshuiBtnClick);
			super.destroy();
		}

	}
}
